<?php

namespace app\admin\controller;

use app\admin\logic\Form2Logic;
use app\admin\model\Form8;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use EasyAdmin\tool\CommonTool;
use jianyan\excel\Excel;
use think\App;
use app\admin\model\Community;

/**
 * @ControllerAnnotation(title="疫苗接种人员管理")
 */
class Form2 extends AdminController
{

    public function __construct(App $app)
    {
        parent::__construct($app);

        $this->model = new \app\admin\model\Form2();
        
        $this->assign('getDosageList', $this->model->getDosageList());

        $this->assign('getCommunityList', Community::getCommunityList());

    }

    /**
     * @NodeAnotation(title="列表")
     */
    public function index()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                return $this->selectList();
            }
            list($page, $limit, $where) = $this->buildTableParames();

            if (!$this->isSuper) {
                $where[] = ['community', '=', $this->user->community_id];
            }

            $count = $this->model
                ->where($where)
                ->count();
            $list = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'name|姓名'                          =>  'require|chs',
                'id_card|身份证号'                   =>  'require|idCard',
                'living|居住地址'                    =>  'require',
                'vaccination_time|接种时间'          =>  'require|date',
                'dosage|接种剂次'                    =>  'require',
                'mobile|手机号码'                    =>  'require|mobile',
            ];
            $this->validate($post, $rule);

            if (strtotime($post['vaccination_time']) > time()) {
                $this->error('接种时间不能大于当前');
            }

            if ($this->model->whereDay('create_time')->where('id_card', $post['id_card'])->count() > 0) {
                $this->error('该身份证号今日已经录入了');
            }

            if (!$this->isSuper) {
                $post['community'] = $this->user->community_id;
            } else {
                empty($post['community']) && $this->error('居住地所属社区不能为空');
            }

            try {
                $save = $this->model->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败:'.$e->getMessage());
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit()
    {
        $row = $this->model->find($this->request->param($this->model->getPk()));
        empty($row) && $this->error('数据不存在');
        if ($this->request->isAjax()) {
            $post = $this->request->post();
            $rule = [
                'name|姓名'                          =>  'require|chs',
                'id_card|身份证号'                   =>  'require|idCard',
                'living|居住地址'                    =>  'require',
                'vaccination_time|接种时间'          =>  'require|date',
                'dosage|接种剂次'                    =>  'require',
                'mobile|手机号码'                    =>  'require|mobile',
            ];
            $this->validate($post, $rule);

            if (strtotime($post['vaccination_time']) > time()) {
                $this->error('接种时间不能大于当前');
            }

            if (!$this->isSuper) {
                $post['community'] = $this->user->community_id;
            } else {
                empty($post['community']) && $this->error('居住地所属社区不能为空');
            }

            try {
                $save = $row->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $this->assign('row', $row);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="删除")
     */
    public function delete()
    {
        $row = $this->model->whereIn($this->model->getPk(), $this->request->param($this->model->getPk()))->select();
        $row->isEmpty() && $this->error('数据不存在');
        try {
            $save = $row->delete();
        } catch (\Exception $e) {
            $this->error('删除失败');
        }
        $save ? $this->success('删除成功') : $this->error('删除失败');
    }

    /**
     * @NodeAnotation(title="疫苗异常反应记录")
     */
    public function form8_index()
    {
        $id = $this->request->param('id/d',0);
        empty($id) && $this->error('提交参数出错');

        $id_card = $this->model->where('id', $id)->value('id_card');

        if (input('selectFields')) {
            return $this->selectList();
        }
        list($page, $limit, $where) = $this->buildTableParames();

        // 关联字段
        $map[] = ['id_card', '=', $id_card];

        if ($this->request->isAjax()) {
            if (input('selectFieds')) {
                return $this->selectList();
            }
            $count = Form8::with(['form2'])
                ->where($where)
                ->where($map)
                ->count();
            $list = Form8::with(['form2'])
                ->where($where)
                ->where($map)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        $this->assign('source_id', $id);
        return $this->fetch();
    }

    /**
     * @NodeAnotation(title="导入")
     * @return mixed
     */
    public function import()
    {
        if ($this->request->isAjax()) {
            $post = [
                'upload_type' => 'local',
                'file'        => $this->request->file('file'),
            ];

            $uploadConfig = sysconfig('upload');
            $rule = [
                'upload_type|指定上传类型有误' => "in:{$uploadConfig['upload_allow_type']}",
                'file|文件'                    => "require|file|fileExt:{$uploadConfig['upload_allow_ext']}|fileSize:{$uploadConfig['upload_allow_size']}",
            ];
            $this->validate($post, $rule);

            $result = Form2Logic::import($post);
            if ($result === false){
                $this->error(self::getError());
            }
            $this->success('导入成功');
        }
        $this->assign('download_url', url('ajax/download_templet', ['name' => '疫苗接种信息导入表.xlsx']));
        return $this->fetch('common/import');
    }
}